package com.nwpu.coursesupport.service.imple;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nwpu.coursesupport.criteria.LessonResourceSearchCriteria;
import com.nwpu.coursesupport.criteria.LessonSearchCriteria;
import com.nwpu.coursesupport.entity.Lesson;
import com.nwpu.coursesupport.entity.LessonResource;
import com.nwpu.coursesupport.entity.Respository;
import com.nwpu.coursesupport.entity.bean.JSONResult;
import com.nwpu.coursesupport.enumeration.RoleType;
import com.nwpu.coursesupport.enumeration.Status;
import com.nwpu.coursesupport.exception.BatchResourceAssignmentException;
import com.nwpu.coursesupport.mapper.LessonMapper;
import com.nwpu.coursesupport.mapper.LessonResourceMapper;
import com.nwpu.coursesupport.mapper.RespositoryMapper;
import com.nwpu.coursesupport.service.AbstractService;
import com.nwpu.coursesupport.service.LessonResourceService;
import com.nwpu.coursesupport.service.param.IDListParam;
import com.nwpu.coursesupport.service.param.IDParam;
import com.nwpu.coursesupport.service.param.LessonResourceServiceParam;
import com.nwpu.coursesupport.view.LessonView;
import com.nwpu.coursesupport.view.ResourceAssignView;

@Service("lessonResourceService")
public class LessonResourceServiceImple extends AbstractService implements LessonResourceService{

	@Autowired
	private LessonResourceMapper lessonResourceMapper;
	@Autowired
	private LessonMapper lessonMapper;
	@Autowired
	private RespositoryMapper respositoryMapper;
	
	protected static Logger logger = LoggerFactory.getLogger(LessonResourceServiceImple.class);
	
	public JSONResult getUnAssignLesson(LessonResourceServiceParam.UnAssignLessonParam p) throws Exception{
		JSONResult rst=new JSONResult();
		rst.fail();
		if(p==null||p.getClassId()<=0||p.getRid()<=0){
			logger.error("参数错误");
			return rst.fail("参数错误");
		}
		
		LessonSearchCriteria sc=new LessonSearchCriteria();
		sc.setClassId(p.getClassId());
		sc.setType(p.getLessonType());
		
		List<Lesson> lessons=this.lessonMapper.find(sc);
		
		List<Integer> ids=this.lessonResourceMapper.findLessonIdById(p.getRid());
		
		Iterator<Lesson> itor=lessons.iterator();
		while(itor.hasNext()){
			Lesson l=itor.next();
			if(ids.contains(l.getId())){
				itor.remove();
			}
		}
		
		rst.success();
		rst.addData("lessons",lessons);
		return rst;
	}
	
	
	//资源分配记录
	public JSONResult assignRecord(IDParam p) throws Exception{
		JSONResult rst=new JSONResult();
		rst.fail();
		
		if(p==null||p.getId()<=0){
			logger.error("参数错误");
			return rst.fail("参数错误");
		}
		Respository r=this.respositoryMapper.findById(p.getId());
		if(r==null){
			logger.error("该资源不存在");
			return rst.fail("该资源不存在");
		}
		
		List<ResourceAssignView> list=this.lessonResourceMapper.assignList(p.getId());
		
		rst.addData("resource", r);
		rst.addData("list", list);
		rst.addData("courseId",r.getCourseId());
		rst.addData("rid", p.getId());
		rst.success();
		return rst;
	}
	
	@Transactional
	public JSONResult batchCreate(LessonResourceServiceParam.BatchCreateParam p) throws BatchResourceAssignmentException{
		JSONResult rst=new JSONResult();
		rst.fail();
		
		if(p==null||p.getLessons()==null||p.getLessons().size()<=0
				||p.getRid()<=0){
			logger.error("参数有误");
			return rst.fail("参数有误");
		}
		//判断该课程是否存在
		List<Integer> lessons=this.lessonMapper.findByIds(p.getLessons());
		if(lessons.size()<=0){
			logger.error("所选择课程不存在");
			return rst.fail("所选择课程不存在");
		}
		Respository r=this.respositoryMapper.findById(p.getRid());
		//判断资源是否存在
		//List<Integer> resources=this.respositoryMapper.findByIds(p.getResources());
		
		/*if(resources.size()<=0){
			return rst.fail("所选资源不存在");
		}*/
		
		List<LessonResource> results=new ArrayList<LessonResource>();
		
		int id=(int) getSession().getAttribute("id");
		String name=(String) getSession().getAttribute("name");
		RoleType roleType=(RoleType) getSession().getAttribute("roleType");
		
		/*BatchAddResourceAssignSearchCriteria sc=null;
		List<Integer> copy=null;
		*/
		Date createDate =new Date();
		
		List<Integer> lessonIds=this.lessonResourceMapper.findLessonIdById(p.getRid());
		p.getLessons().removeAll(lessonIds);
		if(p.getLessons().size()<=0){
			logger.error("该资源已发布到对应的课堂中");
			return rst.fail("该资源已发布到对应的课堂中");
		}
		
		LessonResource lr=null;
		for(Integer item : p.getLessons()){
			lr=new LessonResource();
			lr.setAssignDate(createDate);
			lr.setAssignId(id);
			lr.setLessonId(item);
			lr.setResourceId(p.getRid());
			lr.setRoleType(roleType);
			results.add(lr);
		}
		
		/*for(Integer item : lessons){
			copy=new ArrayList<Integer>(resources);
			sc=new BatchAddResourceAssignSearchCriteria();
			sc.setLessonId(item);
			sc.setRids(resources);
			//判断该课程下是否已经分配
			List<Integer> exits=this.lessonResourceMapper.getResourceByLessonId(sc);
			copy.remove(exits);
			if(copy.size()<=0){
				continue;
			}
			for(Integer rid : copy){
				lr=new LessonResource();
				lr.setAssignDate(createDate);
				lr.setAssignId(id);
				lr.setLessonId(item);
				lr.setResourceId(rid);
				lr.setRoleType(roleType);
				results.add(lr);
			}
		}*/
		if(results.size()<=0){
			logger.error("该资源已发布到对应的课堂中");
			return rst.fail("该资源已发布到对应的课堂中");
		}
		
		if(this.lessonResourceMapper.batchSave(results)!=results.size()){
			logger.error("分配资源失败,并抛出异常BatchResourceAssignmentException");
			throw new BatchResourceAssignmentException("分配资源失败");
		}

		if(r.getIsQuote()!=Status.YES){
			r.setIsQuote(Status.YES);
			if(!this.respositoryMapper.updateQuote(r)){
				logger.error("修改任务状态失败，并抛出异常BatchResourceAssignmentException");
				throw new BatchResourceAssignmentException();
			}
		}
		
		rst.success();
		return rst;
	}
	
	public JSONResult create(LessonResourceServiceParam.CreateParam p) throws Exception{
		JSONResult rst=new JSONResult();
		rst.fail();
		
		if(p==null||p.getLessonId()<=0||p.getResourceId()<=0){
			logger.error("参数错误");
			return rst.fail("参数错误");
		}
		
		Lesson l=this.lessonMapper.findById(p.getLessonId());
		if(l==null){
			
			return rst.fail("该课堂不存在");
		}
		
		Respository r=this.respositoryMapper.findById(p.getResourceId());
		if(r==null){
			logger.error("该资源不存在");
			return rst.fail("该资源不存在");
		}
		
		LessonResource lr=new LessonResource();
		lr.setLessonId(p.getLessonId());
		lr.setResourceId(p.getResourceId());
		int id=(int) getSession().getAttribute("id");
		lr.setAssignId(id);
		lr.setRoleType(RoleType.TEACHER);
		lr.setAssignDate(new Date());
		if(!this.lessonResourceMapper.save(lr)){
			logger.error("保存失败");
			return rst.fail("保存失败");
		}
		
		rst.success();
		return rst;
	}
	
	//课堂分配资源
	public JSONResult assignRecordsInLessonTView(LessonResourceSearchCriteria sc) throws Exception {
		JSONResult rst = new JSONResult();
		rst.fail();

		if (sc == null || sc.getLessonId() <= 0) {
			logger.error("参数有误");
			return rst.fail("参数有误");
		}

		List<Respository> list = this.lessonResourceMapper.findByLessonId(sc);

		rst.addData("list", list);
		rst.addData("lessonId", sc.getLessonId());
		rst.success();
		return rst;
	}
	
	public JSONResult assignRecordsInLessonSView(LessonResourceSearchCriteria sc) throws Exception {
		JSONResult rst = new JSONResult();
		rst.fail();

		if (sc == null || sc.getLessonId() <= 0) {
			logger.error("参数有误");
			return rst.fail("参数有误");
		}

		LessonView view=this.lessonMapper.findViewById(sc.getLessonId());
		if(view==null){
			logger.error("该课程不存在");
			return rst.fail("该课程不存在");
		}
		
		List<Respository> list = this.lessonResourceMapper.findByLessonId(sc);

		rst.addData("list", list);
		rst.addData("lesson", view);
		rst.success();
		return rst;
	}

	public JSONResult remove(IDParam p) throws Exception {
		JSONResult rst = new JSONResult();
		rst.fail();

		if (p == null || p.getId() <= 0) {
			logger.error("参数有误");
			rst.fail("参数有误");
			return rst;
		}

		LessonResource lessonResource = this.lessonResourceMapper.findById(p.getId());
		if (lessonResource == null) {
			logger.error("记录不存在或已被删除");
			return rst.fail("记录不存在或已被删除");
		}

		if (!this.lessonResourceMapper.delete(p.getId())) {
			logger.error("删除失败");
			return rst.fail("删除失败");
		}

		rst.success();
		return rst;
	}

	public JSONResult removeAll(IDListParam p) throws Exception {
		JSONResult rst = new JSONResult();
		rst.fail();

		if (p == null || p.getIds() == null || p.getIds().isEmpty()) {
			logger.error("参数有误");
			rst.fail("参数有误");
			return rst;
		}

		this.lessonResourceMapper.batchDelete(p.getIds());

		rst.success();
		return rst;
	}

}
